<?php
/**
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2017/5/20
 * Time: 16:16
 */
namespace app\service;
use app\api\controller\Base;
use app\models\Models;

Vendor('sms.lib.nusoap');
class Sms extends Base {
    /**
     * 发送验证码
     * @param array $data
     * @return bool
     */
    public function sendCode($data = ['action'=>'','mobile'=>'']){
        // 条件验证
        self::errorMsg($data);
        // 组合传递参数
        $message = ['register'=>'手机注册验证', 'login'=>'用户登录', 'forgetPassword'=>'忘记密码', 'changePassword'=>'修改密码',];
        $code    = rand(1000,9999);//随机生成验证码
        $param['url']      = 'https://api.miaodiyun.com/20150822/industrySMS/sendSMS';
        $param['username'] = '567adcdf31ed40589476839eb91b7108';
        $param['password'] = '27ffc037af18488b904c6ebdd5fdccd1';
        $param['form']     = '';
        $param['to']       = $data['mobile'];
        $param['text']     = "【颜饭】尊敬的用户您好!您正在进行{$message[$data['action']]},验证码:{$code},请于15分钟内输入,工作人员不会向您索取,请勿泄露。";
        $param['time']     = date('Y-m-d H:i:s');
        $param['voice']    = '0|0|0|0';
        // 发送短信请求
        self::smsRequest($param);
        // 将验证码存储于redis中
        $redis = new Redis();
        $redis->set($data['mobile'].$data['action'],60*15,$code);
        return true;
    }

    /**
     * 发送短信请求
     * @param $param
     * @return bool
     */
    protected function smsRequest($param){
        $client = new \soapclient('http://ws.iems.net.cn/GeneralSMS/ws/SmsInterface?wsdl',true);
        $client->soap_defencoding = 'utf-8';
        $client->decode_utf8 = false;
        $client->xml_encoding = 'utf-8';
        $parameters	= array($param['username'],$param['password'],$param['form'],$param['to'],$param['text'],$param['time'],$param['voice']);
        $str = $client->call('clusterSend',$parameters);
        $arr = simplexml_load_string($str,'SimpleXMLElement',LIBXML_NOCDATA);//将xml转换成数组
        if($arr->code != 1000){
            throw new \LogicException($client->getError(),1012);
        }
        return true;
    }

    /**
     * @param array $data
     * 验证数据
     */
    protected function errorMsg($data = []){
        if(empty($data['action']) || empty($data['mobile'])){
            throw new \LogicException('参数错误',1000);
        }
        $user = new Models('user');
        $info = $user->_find(['username'=>$data['mobile']]);
        if($data['action'] == 'register' && $info){
            throw  new \LogicException('您的帐号已存在',1001);
        }
        if($data['action'] == 'forgetPassword' && !$info){
            throw  new \LogicException('该用户尚未注册',1002);
        }
    }
}